<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset=utf-8>
    <meta http-equiv=X-UA-Compatible content="IE=edge">
    <meta name=viewport
        content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=0,shrink-to-fit=no">
    <meta name=format-detection content="telephone=no">
    <meta name=renderer content=webkit>
    <meta name=description content="">
    <meta name=keywords content="">
    <meta http-equiv=Cache-Control content="no-cache, no-store, must-revalidate">
    <meta http-equiv=Pragma content=no-cache>
    <meta http-equiv=Expires content=0>
    <meta name=renderer content=webkit>
    <meta name=mobile-web-app-capable content=yes>
    <meta name=apple-mobile-web-app-status-bar-style content=black>
    <meta name=apple-mobile-web-app-title content=创客匠人>
    <meta http-equiv=x-dns-prefetch-control content=on>
    <script src="https://assets.ckjr001.com/axios-v0.15.3.min.js"></script>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <style>
        .toast-body {
            background: rgba(0, 0, 0, 0.6);
            padding: 20px 0;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 140px;
            font-size: 16px;
            border-radius: 5px;
            text-align: center;
            color: #fff;
            display: none;
        }

        .toast-show {
            display: block !important;
        }

        .img-icon {
            width: 55px;
            height: 55px;
            margin-bottom: 11px;
        }

        .toast-success {
            display: none;
        }

        .toast-error,
        .toast-cancel {
            color: #f76260;
            display: none;
        }
    </style>
</head>

<body>
    <div class="toast-body" id="myToast">
        <div class="toast-success">
            <img class="img-icon"
                src=""
                alt="">
            <div>支付成功</div>
        </div>
        <div class="toast-error">
            <img class="img-icon"
                src=""
                alt="">
            <div>支付失败</div>
        </div>
        <div class="toast-cancel">
            <img class="img-icon"
                src=""
                alt="">
            <div>取消支付</div>
        </div>

    </div>
    <script>
        var apiUrl = 'https://kpapiop.ckjr001.com';
        if (window.location.host.indexOf('kptest.ckjr001.com') > -1 || window.location.host.indexOf('liveauth.myckjr.com') > -1) {
          apiUrl = 'https://kpapi-cs.ckjr001.com';
        } else if (window.location.host.indexOf('formal.ckjr001') > -1) {
          apiUrl = 'https://formalapi.ckjr001.com'
        }
        function showToast(type, time = 2000) {
          document.querySelector('#myToast').classList.add("toast-show");
          var classId = '.toast-' + type;
          document.querySelector(classId).classList.add("toast-show");
          setTimeout(() => {
            document.querySelector('#myToast').classList.remove("toast-show");
            document.querySelector(classId).classList.remove("toast-show");
            window.history.go(-2)
          }, time);
        };
        //获取微信支付和sdk初始化参数
        function getWechatConfig(data) {
          if (sessionStorage.getItem('promotedAccountId')) {
            data.promotedAccountId = sessionStorage.getItem('promotedAccountId')
          }
          axios.post(apiUrl + '/api/payment/wxpayConf', data)
                .then(function (res) {
                  if (res.status == 200 && res.data.statusCode == 200) {
                    initWxConfig(res.data.data.jsConfig, res.data.data.wxpayConfig);
                  }
                })
                .catch(function (error) {
                  console.log(error);
                });
        };
        //初始化sdk并发起支付
        function initWxConfig(configData, payData) {
          wx.config(configData);
          wx.ready(function () {
            wx.chooseWXPay({
              timestamp: payData.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: payData.nonceStr, // 支付签名随机串，不长于 32 位
              package: payData.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: payData.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: payData.paySign, // 支付签名
              success: function (res) {
                showToast('success');
              },
              fail: function (res) {
                showToast('error');
              },
              cancel: function (res) {
                showToast('cancel');
              },
            });
            wx.hideMenuItems({
              menuList: [
                'menuItem:share:appMessage',
                'menuItem:share:timeline',
                'menuItem:share:qq',
                'menuItem:share:weiboApp',
                'menuItem:favorite',
                'menuItem:share:facebook',
                'menuItem:share:QZone',
                'menuItem:editTag',
                'menuItem:delete',
                'menuItem:copyUrl',
                'menuItem:originPage',
                'menuItem:readMode',
                'menuItem:openWithQQBrowser',
                'menuItem:openWithSafari',
                'menuItem:share:email',
                'menuItem:share:brand',
              ]
            });
          });
        }

        function widthdrawLogin(data) {
          var postUrl =  data.type == 'live' ? '/api/sendRed/userAuth' : '/api/members/getPmOpenid';
          console.log('-----授权流程-----')
          axios.post(apiUrl + postUrl, data)
                .then(function (res) {
                  console.log('-----授权流程-成功----',res)
                  if (res.status == 200 && res.data.statusCode == 200) {
                    window.history.go(-2);
                    sessionStorage.setItem("refresh","true");
                  }
                })
                .catch(function (error) {
                  console.log(error);
                });
        }

        function initAuth(paramObj){
          axios.get(apiUrl + '/api/common/getLiveAuthData').then((res)=>{
              let { appid, componentAppid, distribution } = res.data.data;
              //不是直播模块的, 走另一个appid
              if(paramObj.type != 51){
                appid = distribution.appid;
                componentAppid = distribution.componentAppid;
              }
              var backUrl = window.location.href;
              let scope = 'snsapi_base';
              var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURIComponent(backUrl) + '&response_type=code&scope=' + scope + '&component_appid=' + componentAppid + '#wechat_redirect';
              window.location.replace(url)
          })
        }

        window.onload = function () {
            //获取url上带的参数
          var paramStrArr = window.location.href.split('?').length > 1 ? window.location.href.split('?')[1] : [];
          var paramArr = paramStrArr.length > 0 ? paramStrArr.split('&') : [];
          var paramObj = {};
          for (var i = 0; i < paramArr.length; i++) {
            let objArr = paramArr[i].split('=');
            paramObj[objArr[0]] = objArr.length > 1 ? objArr[1] : '';
          }
          if (paramObj.orderId && paramObj.type == 51) {
            localStorage.setItem('ckjrLiveOrderId', paramObj.orderId);
          }
          if (paramObj.orderId && paramObj.type != 51) {
            localStorage.setItem('ckjrDistributionOrderId', paramObj.orderId);
          }
          if (paramObj.code && paramObj.userId) {
            // setTimeout(function () {
            //         //利用iframe的onload事件刷新页面
            //   document.title = '正在授权';
            //   var iframe = document.createElement('iframe');
            //   iframe.src = './static/i/favicon.png'; // 必须
            //   iframe.style.visibility = 'hidden';
            //   iframe.style.width = '1px';
            //   iframe.style.height = '1px';
            //   iframe.onload = function () {
            //     setTimeout(function () {
            //       document.body.removeChild(iframe);
            //     }, 0);
            //   };
            //   document.body.appendChild(iframe);
            // }, 0);
                //提现登录流程
            var data = {
              "code": paramObj.code,
              "companyUserId": paramObj.userId,
              "type": paramObj.type == 51 ? 'live' : 'distribution',
              "url": window.location.href
            }
            widthdrawLogin(data);
            return;
          }
          if (paramObj.code) {
                //分销支付流程
            var data = {
              "code": paramObj.code,
              "orderId": paramObj.type == 51 ? localStorage.getItem('ckjrLiveOrderId') : localStorage.getItem('ckjrDistributionOrderId'),
              "type": paramObj.type == 51 ? 'live' : 'distribution',
              "url": window.location.href
            }
            getWechatConfig(data);
            return;
          }
          initAuth(paramObj);
        };
    </script>
</body>

</html>